<template>
    <div class="nginx-config-formatter">
        <!-- 模板选择 -->
        <div class="template-section">
            <div class="template-row">
                <div 
                    v-for="template in templates" 
                    :key="template.name" 
                    class="template-item"
                    @click="loadTemplate(template.key)"
                >
                    <span class="template-name">{{ template.name }}</span>
                </div>
            </div>
        </div>

        <!-- 主要工作区域 -->
        <div class="main-workspace">
            <div class="workspace-grid">
                <!-- 输入区域 -->
                <div class="workspace-card input-card">
                    <div class="card-header">
                        <div class="card-title">
                            <div class="title-icon">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M11 4H4C3.46957 4 2.96086 4.21071 2.58579 4.58579C2.21071 4.96086 2 5.46957 2 6V20C2 20.5304 2.21071 21.0391 2.58579 21.4142C2.96086 21.7893 3.46957 22 4 22H18C18.5304 22 18.9609 21.7893 19.3359 21.4142C19.7109 21.0391 19.9219 20.5304 19.9219 20V13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M18.5 2.5C18.8978 2.10217 19.4374 1.87868 20 1.87868C20.5626 1.87868 21.1022 2.10217 21.5 2.5C21.8978 2.89782 22.1213 3.43739 22.1213 4C22.1213 4.56261 21.8978 5.10217 21.5 5.5L12 15L8 16L9 12L18.5 2.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            </div>
                            <div class="title-text">
                                <h3>输入配置</h3>
                                <p>粘贴或输入您的 Nginx 配置</p>
                            </div>
                        </div>
                        <div class="card-actions">
                            <c-button size="small" @click="clearAll" class="clear-btn">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M3 6H5H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6H19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                清空
                            </c-button>
                        </div>
                    </div>
                    
                    <div class="card-content">
                        <c-input-text
                            v-model:value="inputConfig"
                            :rows="18"
                            placeholder="在此处粘贴您的 Nginx 配置...
例如：
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
}"
                            multiline
                            monospace
                            @input="handleInput"
                            class="config-input"
                        />
                    </div>
                </div>

                <!-- 输出区域 -->
                <div class="workspace-card output-card">
                    <div class="card-header">
                        <div class="card-title">
                            <div class="title-icon">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2"/>
                                </svg>
                            </div>
                            <div class="title-text">
                                <h3>格式化结果</h3>
                                <p>格式化后的配置将显示在这里</p>
                            </div>
                        </div>
                        <div class="card-actions">
                            <c-button 
                                v-if="outputConfig" 
                                size="small" 
                                @click="copyToClipboard"
                                :loading="isCopying"
                                class="copy-btn"
                            >
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M16 4H18C18.5304 4 19.0391 4.21071 19.4142 4.58579C19.7893 4.96086 20 5.46957 20 6V18C20 18.5304 19.7893 19.0391 19.4142 19.4142C19.0391 19.7893 18.5304 20 18 20H16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M8 20H6C5.46957 20 4.96086 19.7893 4.58579 19.4142C4.21071 19.0391 4 18.5304 4 18V6C4 5.46957 4.21071 4.96086 4.58579 4.58579C4.96086 4.21071 5.46957 4 6 4H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                复制
                            </c-button>
                        </div>
                    </div>
                    
                    <div class="card-content">
                        <c-input-text
                            :value="outputConfig"
                            :rows="18"
                            readonly
                            placeholder="格式化后的配置将显示在这里..."
                            multiline
                            monospace
                            class="config-output"
                        />
                    </div>
                </div>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-bar">
                <div class="action-buttons">
                    <c-button 
                        @click="formatConfig" 
                        :loading="isFormatting" 
                        type="primary"
                        size="large"
                        class="format-btn"
                    >
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                        格式化配置
                    </c-button>
                    <c-button 
                        @click="validateConfig"
                        size="large"
                        class="validate-btn"
                    >
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2"/>
                        </svg>
                        验证配置
                    </c-button>
                </div>
            </div>

            <!-- 验证结果 -->
            <div v-if="validationResult" class="validation-result">
                <div class="result-card" :class="validationResult.isValid ? 'success' : 'error'">
                    <div class="result-icon">
                        <svg v-if="validationResult.isValid" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2"/>
                        </svg>
                        <svg v-else width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.29 3.86L1.82 18A2 2 0 0 0 3.54 21H20.46A2 2 0 0 0 22.18 18L13.71 3.86A2 2 0 0 0 10.29 3.86Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M12 9V13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M12 17H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                    <div class="result-content">
                        <h4 class="result-title">
                            {{ validationResult.isValid ? '配置验证通过' : '配置验证失败' }}
                        </h4>
                        <p v-if="validationResult.message" class="result-message">
                            {{ validationResult.message }}
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useCopy } from '@/composable/copy';

const inputConfig = ref('');
const outputConfig = ref('');
const isFormatting = ref(false);
const isCopying = ref(false);
const validationResult = ref<{ isValid: boolean; message?: string } | null>(null);

const { copy } = useCopy();

const templates = [
    {
        key: 'static',
        name: '静态网站',
        description: '基本的静态文件服务配置'
    },
    {
        key: 'spa',
        name: 'SPA 应用',
        description: '单页应用配置，支持前端路由'
    },
    {
        key: 'proxy',
        name: '反向代理',
        description: 'API 反向代理配置'
    },
    {
        key: 'ssl',
        name: 'SSL 配置',
        description: 'HTTPS 安全配置'
    }
];

const handleInput = () => {
    validationResult.value = null;
};

// 简单的格式化函数
const formatNginxConfig = (config: string): string => {
    try {
        if (!config.trim()) {
            throw new Error('配置内容不能为空');
        }

        // 基础格式化逻辑
        let formatted = config
            .replace(/\s*\{\s*/g, ' {\n')
            .replace(/\s*\}\s*/g, '\n}\n')
            .replace(/;\s*/g, ';\n')
            .replace(/\n\s*\n/g, '\n')
            .trim();

        // 添加缩进
        const lines = formatted.split('\n');
        let indentLevel = 0;
        const formattedLines = lines.map(line => {
            const trimmed = line.trim();
            if (trimmed.endsWith('}')) {
                indentLevel = Math.max(0, indentLevel - 1);
            }
            const indented = '    '.repeat(indentLevel) + trimmed;
            if (trimmed.endsWith('{')) {
                indentLevel++;
            }
            return indented;
        });

        return formattedLines.join('\n');
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '格式化失败';
        throw new Error(`格式化失败: ${errorMessage}`);
    }
};

// 简单的验证函数
const validateNginxConfig = (config: string): { isValid: boolean; message?: string } => {
    try {
        if (!config.trim()) {
            return {
                isValid: false,
                message: '配置内容不能为空'
            };
        }

        // 检查大括号匹配
        const openBraces = (config.match(/\{/g) || []).length;
        const closeBraces = (config.match(/\}/g) || []).length;
        
        if (openBraces !== closeBraces) {
            return {
                isValid: false,
                message: `大括号不匹配: 开始括号 ${openBraces} 个，结束括号 ${closeBraces} 个`
            };
        }

        return {
            isValid: true,
            message: '配置语法正确'
        };
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '验证失败';
        return {
            isValid: false,
            message: `验证失败: ${errorMessage}`
        };
    }
};

const formatConfig = async () => {
    if (!inputConfig.value.trim()) {
        return;
    }

    isFormatting.value = true;
    try {
        const formatted = formatNginxConfig(inputConfig.value);
        outputConfig.value = formatted;
        validationResult.value = null;
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '格式化失败';
        outputConfig.value = `格式化失败: ${errorMessage}`;
    } finally {
        isFormatting.value = false;
    }
};

const validateConfig = () => {
    if (!inputConfig.value.trim()) {
        return;
    }

    try {
        const result = validateNginxConfig(inputConfig.value);
        validationResult.value = {
            isValid: result.isValid,
            message: result.message
        };
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '验证失败';
        validationResult.value = {
            isValid: false,
            message: errorMessage
        };
    }
};

const clearAll = () => {
    inputConfig.value = '';
    outputConfig.value = '';
    validationResult.value = null;
};

const copyToClipboard = async () => {
    if (!outputConfig.value) return;
    
    isCopying.value = true;
    try {
        await copy(outputConfig.value);
    } finally {
        isCopying.value = false;
    }
};

const loadTemplate = (type: string) => {
    const templateConfigs: Record<string, string> = {
        static: `server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}`,
        spa: `server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://localhost:3000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}`,
        proxy: `server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}`,
        ssl: `server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;
    root /var/www/html;
    index index.html;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    location / {
        try_files $uri $uri/ /index.html;
    }
}`
    };

    inputConfig.value = templateConfigs[type] || '';
    outputConfig.value = '';
    validationResult.value = null;
};
</script>

<style scoped>
.nginx-config-formatter {
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 2rem 1rem;
}

/* 模板区域 */
.template-section {
    margin: 0 2rem 2rem 2rem;
}

.template-row {
    display: flex;
    justify-content: center;
    gap: 1rem;
    flex-wrap: wrap;
}

.template-item {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    padding: 0.75rem 1.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    font-size: 0.9rem;
    font-weight: 500;
}

.template-item:hover {
    background: rgba(255, 255, 255, 0.15);
    transform: translateY(-1px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.template-name {
    white-space: nowrap;
}

/* 主要工作区域 */
.main-workspace {
    margin: 0 2rem;
}

.workspace-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    margin-bottom: 2rem;
}

@media (max-width: 1200px) {
    .workspace-grid {
        grid-template-columns: 1fr;
    }
}

.workspace-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
}

.workspace-card:hover {
    box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1.5rem;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-bottom: 1px solid #e2e8f0;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.title-icon {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    padding: 0.5rem;
    color: white;
}

.title-text h3 {
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0;
    color: #1e293b;
}

.title-text p {
    font-size: 0.9rem;
    margin: 0.25rem 0 0 0;
    color: #64748b;
}

.card-actions {
    display: flex;
    gap: 0.5rem;
}

.card-content {
    padding: 1.5rem;
}

.config-input,
.config-output {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 0.9rem;
    line-height: 1.5;
}

.config-input:focus,
.config-output:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 操作按钮区域 */
.action-bar {
    display: flex;
    justify-content: center;
    margin-bottom: 2rem;
}

.action-buttons {
    display: flex;
    gap: 1rem;
}

.format-btn,
.validate-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.format-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
}

.format-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.validate-btn {
    background: white;
    border: 2px solid #e2e8f0;
    color: #64748b;
}

.validate-btn:hover {
    border-color: #667eea;
    color: #667eea;
    transform: translateY(-1px);
}

.clear-btn,
.copy-btn {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.5rem 0.75rem;
    border-radius: 6px;
    font-size: 0.85rem;
    transition: all 0.2s ease;
}

.clear-btn {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.clear-btn:hover {
    background: #fee2e2;
    border-color: #fca5a5;
}

.copy-btn {
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    color: #0284c7;
}

.copy-btn:hover {
    background: #e0f2fe;
    border-color: #7dd3fc;
}

/* 验证结果 */
.validation-result {
    max-width: 800px;
    margin: 0 auto;
}

.result-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1.5rem;
    border-radius: 12px;
    background: white;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.result-card.success {
    border-left: 4px solid #10b981;
    background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
}

.result-card.error {
    border-left: 4px solid #ef4444;
    background: linear-gradient(135deg, #fef2f2 0%, #fef2f2 100%);
}

.result-icon {
    flex-shrink: 0;
}

.result-card.success .result-icon {
    color: #10b981;
}

.result-card.error .result-icon {
    color: #ef4444;
}

.result-content {
    flex: 1;
}

.result-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0 0 0.5rem 0;
    color: #1e293b;
}

.result-message {
    font-size: 0.9rem;
    margin: 0;
    color: #64748b;
    line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .nginx-config-formatter {
        padding: 1rem 0.5rem;
    }
    
    .page-title {
        font-size: 2rem;
    }
    
    .header-content {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .template-row {
        flex-direction: column;
        align-items: center;
    }
    
    .template-item {
        width: 100%;
        max-width: 300px;
        justify-content: center;
    }
    
    .action-buttons {
        flex-direction: column;
        width: 100%;
    }
    
    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }
    
    .card-actions {
        align-self: flex-end;
    }
    
    .workspace-grid {
        gap: 1rem;
    }
    
    .card-content {
        padding: 1rem;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 1.5rem;
    }
    
    .page-subtitle {
        font-size: 1rem;
    }
    
    .template-item {
        padding: 0.5rem 1rem;
        font-size: 0.85rem;
    }
    
    .title-text h3 {
        font-size: 1rem;
    }
    
    .title-text p {
        font-size: 0.8rem;
    }
}
</style>
